<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="header-content">
        <view class="header-left">
          <text class="header-title">购物车 ({{ cartItems.length }})</text>
        </view>
        <view class="header-right">
          <text class="edit-btn" @tap="toggleEdit">{{ isEditing ? '完成' : '编辑' }}</text>
        </view>
      </view>
    </view>

    <!-- 购物车内容 -->
    <view v-if="cartItems.length === 0" class="empty-cart">
      <text class="empty-icon">🛒</text>
      <text class="empty-text">购物车还是空的</text>
      <view class="go-shopping-btn" @tap="goToHome">
        <text class="btn-text">去逛逛</text>
      </view>
    </view>

    <view v-else class="cart-content">
      <!-- 购物车商品列表 -->
      <scroll-view class="cart-scroll" scroll-y="true">
        <view class="cart-items">
          <view v-for="item in cartItems" :key="item.cartId" class="cart-item">
            <view class="item-checkbox" @tap="toggleItemSelect(item.cartId)">
              <view class="checkbox" :class="{ checked: item.selected }">
                <text v-if="item.selected" class="check-mark">✓</text>
              </view>
            </view>

            <image class="item-image" :src="BASE_URL + item.img" mode="aspectFill"></image>

            <view class="item-info">
              <text class="item-name">{{ item.goodName }}</text>
              <text class="item-spec">{{ item.standard }}</text>
              <view class="item-price-row">
                <text class="item-price">¥{{ item.price }}</text>
                
                <view class="quantity-controls">
                  <view 
                    class="quantity-btn" 
                    :class="{ disabled: item.count <= 1 }"
                    @tap="updateQuantity(item.cartId, -1)"
                  >
                    <text class="btn-text">-</text>
                  </view>
                  <text class="quantity-text">{{ item.count }}</text>
                  <view class="quantity-btn" @tap="updateQuantity(item.cartId, 1)">
                    <text class="btn-text">+</text>
                  </view>
                </view>
              </view>
            </view>

            <view class="item-delete" @tap="removeItem(item.cartId)">
              <text class="delete-icon">🗑️</text>
            </view>
          </view>
        </view>

        <!-- 推荐商品 -->
        <view class="recommend-section">
          <text class="recommend-title">为你推荐</text>
          <view class="recommend-grid">
            <view v-for="i in 4" :key="i" class="recommend-item" @tap="goToProduct(i)">
              <image class="recommend-image" src="https://images.unsplash.com/photo-1544787219-7f47ccb76574?w=120&h=120&fit=crop" mode="aspectFill"></image>
              <view class="recommend-info">
                <text class="recommend-name">推荐茶叶 {{ i }}</text>
                <text class="recommend-price">¥99</text>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 底部结算栏 -->
    <view v-if="cartItems.length > 0" class="checkout-bar">
      <view class="checkout-left">
        <view class="select-all" @tap="toggleSelectAll">
          <view class="checkbox" :class="{ checked: selectAll }">
            <text v-if="selectAll" class="check-mark">✓</text>
          </view>
          <text class="select-all-text">全选</text>
        </view>
      </view>

      <view class="checkout-right">
        <view class="total-info">
          <text class="total-quantity">共{{ totalQuantity }}件商品</text>
          <text class="total-price">¥{{ totalPrice.toFixed(2) }}</text>
        </view>
        <view 
          class="checkout-btn" 
          :class="{ disabled: selectedItems.length === 0 }"
          @tap="goToCheckout"
        >
          <text class="btn-text">结算 ({{ selectedItems.length }})</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
const BASE_URL = getApp().$vm.$global.baseURL

export default {
  data() {
    return {
      BASE_URL,
      isEditing: false,
      selectAll: false,
      cartItems: []
    }
  },

  computed: {
    selectedItems() {
      return this.cartItems.filter(item => item.selected)
    },
    
    totalPrice() {
      return this.selectedItems.reduce((sum, item) => sum + item.price * item.count, 0)
    },
    
    totalQuantity() {
      return this.selectedItems.reduce((sum, item) => sum + item.count, 0)
    }
  },

  watch: {
    cartItems: {
      handler() {
        // 检查是否全选
        this.selectAll = this.cartItems.length > 0 && this.cartItems.every(item => item.selected)
      },
      deep: true
    }
  },

  methods: {
    toggleEdit() {
      this.isEditing = !this.isEditing
      uni.showToast({
        title: this.isEditing ? '进入编辑模式' : '退出编辑模式',
        icon: 'none',
        duration: 1000
      })
    },

    updateQuantity(cartId, change) {
      const item = this.cartItems.find(item => item.cartId === cartId)
      if (item) {
        const newCount = item.count + change
        if (newCount >= 1) {
          item.count = newCount
          uni.showToast({
            title: change > 0 ? '数量+1' : '数量-1',
            icon: 'none',
            duration: 800
          })
          // TODO: 如果有接口更新数量，这里可以调用接口同步数量
        } else {
          uni.showToast({
            title: '商品数量不能少于1',
            icon: 'none'
          })
        }
      }
    },

    toggleItemSelect(cartId) {
      const item = this.cartItems.find(item => item.cartId === cartId)
      if (item) {
        item.selected = !item.selected
        uni.showToast({
          title: item.selected ? '已选中' : '已取消选中',
          icon: 'none',
          duration: 800
        })
      }
    },

    removeItem(cartId) {
      console.log('准备删除购物车商品，cartId:', cartId)
      uni.showModal({
        title: '确认删除',
        content: `确定要删除该商品吗？`,
        confirmText: '删除',
        confirmColor: '#ff4757',
        success: (res) => {
          if (res.confirm) {
            uni.request({
              url: `${BASE_URL}/api/cart/${cartId}`,
              method: 'DELETE',
              success: (res) => {
                console.log('删除接口返回:', res)
                if (res.data.code === '200' || res.data.success === true) {
                  uni.showToast({
                    title: '删除成功',
                    icon: 'success',
                    duration: 1500
                  })
                  this.fetchCartItems()
                } else {
                  uni.showToast({
                    title: '删除失败: ' + (res.data.msg || '未知错误'),
                    icon: 'none'
                  })
                }
              },
              fail: (err) => {
                console.error('删除请求失败:', err)
                uni.showToast({
                  title: '请求失败',
                  icon: 'none'
                })
              }
            })
          }
        }
      })
    },

    toggleSelectAll() {
      this.selectAll = !this.selectAll
      this.cartItems.forEach(item => {
        item.selected = this.selectAll
      })
      
      uni.showToast({
        title: this.selectAll ? '已全选' : '已取消全选',
        icon: 'none',
        duration: 1000
      })
    },

    goToCheckout() {
      if (this.selectedItems.length === 0) {
        uni.showToast({
          title: '请选择要结算的商品',
          icon: 'none',
          duration: 2000
        })
        return
      }
      
      const selectedData = JSON.stringify(this.selectedItems)
      uni.navigateTo({
        url: `/pages/checkout/checkout?items=${encodeURIComponent(selectedData)}`
      })
    },

    goToHome() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    },

    goToProduct(productId) {
      uni.navigateTo({
        url: `/pages/product/product?id=${productId}`
      })
    },

    fetchCartItems() {
      const userInfo = uni.getStorageSync('userInfo') || {}
      const userId = userInfo.id
      if (!userId) {
        uni.showToast({ title: '请先登录', icon: 'none' })
        this.cartItems = []
        return
      }
      console.log('加载购物车，用户ID:', userId)
      uni.request({
        url: `${BASE_URL}/api/cart/userid/${userId}`,
        method: 'GET',
        success: (res) => {
          console.log('购物车数据返回:', res)
          if (res.data.code === '200' || res.data.success === true) {
            const data = res.data.data || []
            this.cartItems = data.map(item => ({
              id: item.goodId,
              cartId: item.id,
              goodName: item.goodName,
              price: item.price,
              img: item.img,
              standard: item.standard,
              count: item.count,
              discount: item.discount || 1,
              selected: true
            }))
          } else {
            this.cartItems = []
            uni.showToast({ title: '加载购物车失败', icon: 'none' })
          }
        },
        fail: (err) => {
          console.error('请求购物车失败:', err)
          uni.showToast({ title: '请求失败', icon: 'none' })
          this.cartItems = []
        }
      })
    }
  },

  onLoad() {
    this.fetchCartItems()
  },

  onShow() {
    this.fetchCartItems()
  }
}
</script>



<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航 */
.header {
  background-color: white;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 50;
}

.header-content {
  max-width: 750rpx;
  margin: 0 auto;
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.edit-btn {
  font-size: 28rpx;
  color: #ff4757;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  background-color: rgba(255, 71, 87, 0.1);
}

/* 空购物车 */
.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
  min-height: calc(100vh - 200rpx);
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 40rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 60rpx;
}

.go-shopping-btn {
  background: linear-gradient(45deg, #388f4a, #4caf50);
  color: white;
  padding: 24rpx 60rpx;
  border-radius: 50rpx;
  box-shadow: 0 8rpx 20rpx rgba(56, 143, 74, 0.3);
}

.btn-text {
  font-size: 28rpx;
  color: white;
}

/* 购物车内容 */
.cart-content {
  padding-bottom: 160rpx;
}

.cart-scroll {
  max-height: calc(100vh - 280rpx);
}

.cart-items {
  padding: 30rpx;
}

.cart-item {
  background-color: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  position: relative;
}

.cart-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 6rpx;
  background: linear-gradient(to bottom, #388f4a, #4caf50);
  border-radius: 20rpx 0 0 20rpx;
}

.item-checkbox {
  margin-right: 20rpx;
}

.checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 3rpx solid #ddd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.checkbox.checked {
  background-color: #388f4a;
  border-color: #388f4a;
  transform: scale(1.1);
}

.check-mark {
  font-size: 24rpx;
  color: white;
  font-weight: bold;
}

.item-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 16rpx;
  margin-right: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 8rpx;
  display: block;
  line-height: 1.4;
}

.item-spec {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 20rpx;
  display: block;
  background-color: #f8f9fa;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  display: inline-block;
}

.item-price-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.item-price {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff4757;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 20rpx;
  background-color: #f8f9fa;
  border-radius: 25rpx;
  padding: 8rpx;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  border: 2rpx solid #e9ecef;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
  transition: all 0.3s ease;
}

.quantity-btn:active {
  transform: scale(0.95);
  background-color: #388f4a;
  border-color: #388f4a;
}

.quantity-btn:active .btn-text {
  color: white;
}

.quantity-btn.disabled {
  opacity: 0.5;
  background-color: #f8f9fa;
}

.quantity-btn.disabled:active {
  transform: none;
  background-color: #f8f9fa;
  border-color: #e9ecef;
}

.quantity-btn.disabled:active .btn-text {
  color: #999;
}

.quantity-text {
  font-size: 28rpx;
  font-weight: 600;
  min-width: 60rpx;
  text-align: center;
  color: #333;
}

.item-delete {
  margin-left: 20rpx;
  padding: 10rpx;
}

.delete-icon {
  font-size: 32rpx;
  color: #ff4757;
}

/* 推荐商品 */
.recommend-section {
  background-color: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin: 0 30rpx 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.recommend-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  display: block;
  position: relative;
}

.recommend-title::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: -10rpx;
  width: 60rpx;
  height: 4rpx;
  background: linear-gradient(45deg, #388f4a, #4caf50);
  border-radius: 2rpx;
}

.recommend-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20rpx;
}

.recommend-item {
  text-align: center;
  padding: 10rpx;
  border-radius: 12rpx;
  transition: all 0.3s ease;
}

.recommend-item:active {
  transform: scale(0.95);
  background-color: #f8f9fa;
}

.recommend-image {
  width: 100%;
  height: 120rpx;
  border-radius: 12rpx;
  margin-bottom: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.recommend-name {
  font-size: 22rpx;
  color: #333;
  margin-bottom: 8rpx;
  display: block;
  line-height: 1.3;
}

.recommend-price {
  font-size: 24rpx;
  color: #ff4757;
  font-weight: bold;
}

/* 底部结算栏 */
.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  border-top: 1rpx solid #e0e0e0;
  padding: 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.checkout-left {
  display: flex;
  align-items: center;
}

.select-all {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.select-all-text {
  font-size: 28rpx;
  color: #666;
}

.checkout-right {
  display: flex;
  align-items: center;
  gap: 30rpx;
}

.total-info {
  text-align: right;
}

.total-quantity {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 8rpx;
}

.total-price {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.checkout-btn {
  background: linear-gradient(45deg, #388f4a, #4caf50);
  color: white;
  padding: 24rpx 48rpx;
  border-radius: 50rpx;
  font-size: 28rpx;
  font-weight: 500;
  box-shadow: 0 8rpx 20rpx rgba(56, 143, 74, 0.3);
  transition: all 0.3s ease;
}

.checkout-btn:active {
  transform: scale(0.95);
}

.checkout-btn.disabled {
  background: #ccc;
  box-shadow: none;
}

.checkout-btn.disabled:active {
  transform: none;
}
</style>
